<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends MY_Controller {

	/**
	 * @var ConsumerOrderModel
	 */
	public $mOrder = null;
	
	/**
	 * @var MerchantUserModel
	 */
	public $mMerchant = null;
	
	public function __construct(){
		parent::__construct();	
		$this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
		$this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
	}
	
	/**
	 * 首页
	 */
	public function index(){

		$data = [
             'status' => $this->mOrder->status(),
             'expenseType' => $this->mOrder->expenseType(),
             'payType' => $this->mOrder->payType()
		];
		
		$this->view('order/home', $data, 'datatable,datepicker,select2,datetimepicker');
	}
	
	/**
	 * 获取列表
	 */
	public function getList(){
        $data = $this->mOrder->adminPcGetOrderList();
        if ($data['data']){
            foreach ($data['data'] as $k => $v){
                $data['aaData'][$k][] = $v['code'];
                $data['aaData'][$k][] = $v['merchant_day_index'] > 0?'#'.$v['merchant_day_index']:'';
                $data['aaData'][$k][] = $v['merchant'];
                $data['aaData'][$k][] = $v['consumer'];
                $data['aaData'][$k][] = $this->mOrder->expenseType($v['expense_type']);
                $data['aaData'][$k][] = $this->mOrder->payType($v['pay_type']);
                $data['aaData'][$k][] = $v['total_amount'];
                $data['aaData'][$k][] = $v['reality_amount'];
                $data['aaData'][$k][] = dateFormat($v['addtime'], true);
                $data['aaData'][$k][] = $v['pay_time']?dateFormat($v['pay_time'], true):'';

				$time_expire = ($v['addtime'] + getCustomConfig('order_expire') * 60) - time();
                if ($time_expire <= 0 && in_array($v['status'],array(1))){
                    //订单状态为待支付 时，才失效
                    $v['status'] = 7;//通用失效订单
                }
				
                if ($v['expense_type'] == 2){
                    $data['aaData'][$k][] = $this->mOrder->storeStatus($v['status'], true);
                }else{
                    $data['aaData'][$k][] = $this->mOrder->status($v['status'], true);
                }
//                $data['aaData'][$k][] = $this->mOrder->status($v['status'], true);
                $btnConfig = adminCreateBtn(array(
                    'label' => '查看',
                    'attr' => array(
                        'href' => getUrl('order/home/details?id='.$v['id']),
                        'class' => 'btn green-stripe btn-xs default'
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'order',
                        'key' => 'home-details'
                    )
                ));
                if ($v['status'] == 7){
                    $btnConfig .=' '.adminCreateBtn(array(
                        'label' => '删除',
                        'attr' => array(
                            'href' => getUrl('order/home/deleteOrder?id='.$v['id']),
                            'class' => 'btn btn-xs red-stripe default ajax-request-btn',
                            'alert-message' => '是否确认删除订单？'
                        ),
                        'tag' => 'a',
                        'permissions' => array(
                            'module' => 'order',
                            'key' => 'home-delete'
                        )
                    ));
                }
                $data['aaData'][$k][] = $btnConfig;
            }
        }
		unset($data['data']);
		echo json_encode($data);
	}
	
	/**
	 * 详情
	 */
	public function details(){
		$id = get('id');
		$merchantId = get('merchant_id');
		if( ! is_numeric($id)){
			show_404();			
		}
		$info = $this->mOrder->getInfo($id);  // 订单信息
        if (empty($info)){
            show_404();
        }
        $this->loadModel('AdmSettingModel', 'mAdm', 'admin');
        $this->loadModel('AdmShippingModel', 'mShipping', 'admin');

        $oP = $this->mOrder->getOrderProductInfoByIds(array(), $id); // 订单商品信息

//        if ($info['expense_type'] == 2){
//            $buttons = $this->mOrder->storeStatus($info['status'], false, true); // 操作按钮
//        }else{
//            $buttons = $this->mOrder->status($info['status'], false, true); // 操作按钮
//        }

        if ($info['after_sale'] != 2){
            $buttons = $this->mOrder->status($info['status'], false, true); // 操作按钮

        }else{
            $buttons = '';
        }
        $province = $this->mAdm->getLocationByPid(1);  // 获取省份
        $ship = $this->mShipping->getList();    // 获取快递公司
//        $requestData = [
//            "OrderCode"=>$info['code'],
//            "ShipperCode"=>$info['express_param']['express_code'],
//            "LogisticCode"=>$info['express_param']['express_bill']
//        ];
//        $kd = KDNiao()->getOrderTracesByJson($requestData);  // 查看物流信息
        $reason = $this->mAdm->get('aftersale_reason');
        $data = array(
            'info' => $info,
            'oP' => empty($oP) ? array() : $oP[$id],
            'buttons' => $buttons,
            'province' => $province,
            'ship' => $ship,
            'service_status' => $this->mOrder->serviceType($info['after_sale']),
            'reason' => json_decode($reason,true),
//            'kd' => json_decode($kd, true),
            'backUrl' => $merchantId?getUrl('member/merchant/details?id='.$merchantId):getUrl('order/home'),
            'title' => '订单详情'
        );
		$this->view('order/details', $data, 'datatable,validation,region,select2,webuploader');
	}

    /**
     * 获取订单详情
     */
    public function getInfo(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf);
        $id = (int)post('id');
        $info = $this->mOrder->getInfo($id);  // 订单信息
        if (!$info){
            $this->ajaxReturn(0, '订单不存在');
        }
        $data = array(
            'province_id' => $info['province_id'],
            'city_id' => $info['city_id'],
            'county_id' => $info['county_id'],
            'address' => $info['address'],
            'contacts' => $info['contacts'],
            'mobile' => $info['mobile'],
        );
        unset($info);
        exit(json_encode($data));
    }

    /**
     * 获取单个商品详情
     */
    public function getOrderProductInfo(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf);
        $id = (int)post('id');
        $info = $this->mOrder->getOrderProductInfo($id);  // 订单信息
        if (!$info){
            $this->ajaxReturn(0, '商品不存在');
        }
        exit(json_encode($info));
    }

	/**
     * 获取操作记录
     */
	public function getOrderLogList(){
        $data = $this->mOrder->adminPcGetOrderLogList();
        if ($data['data']){
            foreach ($data['data'] as $k => $v){
                $data['aaData'][$k][] = $this->mOrder->ORDER_LOG_TYPE[$v['type']].'：'.$v['user_name'];
                $data['aaData'][$k][] = dateFormat($v['addtime'], true);
                $data['aaData'][$k][] = $v['order_status'];
                $data['aaData'][$k][] = $v['note'];
            }
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 接单
     */
    public function accept(){
            //表单验证
            $vConf = array(
                array('id', 'id', 'required|is_natural_no_zero'),
//            array('note', '操作备注', 'required'),
            );
            $this->formDataValidation($vConf);
            $id = (int)post('id');
            $note = trim(post('note'));
            $note = $note?$note:'后台操作接单';


            //订单信息
            $info = $this->mOrder->getInfoForDeliveryman($id);
            //是否在营业时间端内
            $tBusiness = $this->mMerchant->getBusinessMerchant(array($info['merchant_id']));
            if(!isset($tBusiness[$info['merchant_id']])){
                $this->ajaxReturn(0, '请在营业时间段内接单~');
            }

            if(strtotime(date('Y-m-d', $info['expect_arrive_time'])) > strtotime(date('Y-m-d', time()))){
                $this->ajaxReturn(0, '您暂时不能接受此预订单~');
            }
            //商品信息
            $productList = $this->mOrder->getOrderProductList($id);
            if(!$productList){
                $this->ajaxReturn(0, '订单不存在');
            }

            $product = array();
            $income = $info['deliveryman_income'];//配送员收入

            foreach ($productList as $pro){
                $product[] = array(
                    'name' => $pro['name'].$pro['property_new'],
                    'quantity' => $pro['quantity']
                );
            }

            if(!$info){
                $this->ajaxReturn(0, '订单不存在');
            }

            //验证订单状态 及 配送方式
            if($info['status'] != 2 || $info['expense_type'] != 1){
                $this->ajaxReturn(0, '请勿重复操作或刷新后操作');
            }

            $this->db->trans_begin();

            //减库存
            $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
            $reduce_stock = $this->mSetting->get('reduce_stock');
            if($reduce_stock == 2){//发货减库存
                $result = $this->mOrder->reduceStocks($id);
                if($result['status'] == 0){
                    $this->db->trans_rollback();
                    $this->ajaxReturn(0, $result['message']);
                }
            }
            $merchantTakeTime = microtime(true);

            //保存订单信息
            if(!($this->mOrder->save(array('status' => 3,'print_status' => 1,'merchant_take_time'=>$merchantTakeTime), 0, $id))){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '接单失败');
            }
            //赠送代金券
            if ( ! $this->GiveCoupon($id, $info['reality_amount'], $info['consumer_id'])){
                $this->db->trans_rollback();
                $this->appReturn(0, '代金劵赠送失败');
            }
            $this->db->trans_commit();

            //订单编号
            $count = $this->mOrder->getMerchantOrderCount($info['merchant_id'], $merchantTakeTime);
            //保存订单信息
            if(!($this->mOrder->save(array('merchant_day_index' => $count), 0, $id))){
                $this->ajaxReturn(0, '接单失败');
            }
            //平台配送
            if($info['shipping_type'] == 2) {
                //配送员接单过期时间
                $rob_expect_time = $this->mSetting->get('rob_expect_time', 'deliveryman');
                //预计送达时间 = 预计送达时间 - 下单时间 - 配送员过期时间 - 商家接单过期时间
                $timediff = $info['expect_arrive_time'] - time();
                $minute = floor($timediff % 86400 / 60);
                $tTime = (int)getCustomConfig('expect_take_time') + $rob_expect_time;//预计送达时间
                $expect_arrive_time = $minute - $tTime;

                if ($expect_arrive_time < 0 || !is_numeric($expect_arrive_time)) {
                    $expect_arrive_time = 0;

                }
                //生成运单
                $this->loadModel('DlnOrderModel', 'mDlnOrder', 'deliveryman');
                $distance = getDistance($info['shop_latitude'], $info['shop_longitude'], $info['latitude'], $info['longitude']);
                $result = $this->mDlnOrder->add($info['merchant_id'], $info['consumer_id'], 2, '#'.$count, $id, $info['province'],
                    $info['city'], $info['county'], $info['shop_longitude'], $info['shop_latitude'], $info['merchant'],
                    $info['shop_address'], $info['store_tel'], $info['contacts'], $info['mobile'], $info['address'],
                    $info['longitude'], $info['latitude'], $product, $info['remark'], $expect_arrive_time,
                    $income, $weight = 0, $distance);
                if ($result['status'] != 1) {
                    $this->ajaxReturn(0, $result['message']);
                }
             }
            //记录订单操作日志
            if(!($this->mOrder->saveOrderLog($id, '待收货', $note, $this->port, $this->userId))){
//                $this->db->trans_rollback();
                $this->ajaxReturn(0, '受理失败');
            }

            //推送消息
            $msgData = array(
                'title' => '商家已受理',
                'content' => '商家正在配送中',
                'addtime' => time(),
            );
            $this->loadModel('ConsumerMessageModel', 'mMessage', 'consumer');
            if(!($this->mMessage->save($msgData, 0, $id))){
//                $this->db->trans_rollback();
                $this->ajaxReturn(0, '消息保存失败');
            }
            jpush($msgData['title'], $msgData['content'], 1, array($info['jpush_code']), 3, $id, $info['expense_type']);

            //平台配送 通知配送员
            if($info['shipping_type'] == 2){
                $this->loadModel('DlnUserModel', 'mDlnUser', 'deliveryman');

                $distance = $this->mSetting->get('deliveryman_range', 'deliveryman');//配送员接单范围
                $distance = $distance>0 ? round($distance/1000,2):0;
                $dlnData = $this->mDlnUser->getDlnUser($info['latitude'], $info['longitude'], $distance);
                if($dlnData){
                    $dlnJpush = array_column($dlnData, 'jpush_code');
                    deliverymanJpush('新订单提醒','来新订单啦~赶快去抢单吧', 2, $dlnJpush, 0, 'new_order.mp3', 1);
                }
            }


            $this->ajaxReturn(1,'接单成功', NULL, getUrl('order/home/details?id='.$id));
        }

    /**
     * 下单即可送代金劵
     */
    private function GiveCoupon($orderId, $realityAmount,$consumerId){
        if ( ! $orderId || !$consumerId){
            return false;
        }

        $this->loadModel('ConsumerPromotionModel', 'mPromotion','consumer');
        $this->loadModel('MerchantPromotionModel', 'mMerPromotion','merchant');

        $tCoupon = $this->mMerPromotion->getCouponListByMerchantIds(array($this->userId));
        if ( ! $tCoupon){
            return true;
        }

        $tGiveCoupon = array();
        if (!isset($tCoupon[$this->userId])){
            //不存在
            return true;
        }

        if ($realityAmount >= $tCoupon[$this->userId]['receive']){
            //实际支付金额 > 代金劵领取条件
            //装入代金劵批量
            $tGiveCoupon[] = array(
                'merchant_id'	=> $this->userId,
                'consumer_id'	=> $consumerId,
                'order_id'		=> $orderId,
                'money'			=> $tCoupon[$this->userId]['money'],
                'valid_hour'	=> $tCoupon[$this->userId]['valid_hour'],
                'send_time'		=> time(),
                'status'		=> 1,
                'used_time'		=> 0,
                'condition'		=> $tCoupon[$this->userId]['condition'],
                'use_end_time'	=> time() + $tCoupon[$this->userId]['valid_hour'] * 3600,
            );
        }

        if ($tGiveCoupon){
            if ( ! $this->mPromotion->saveBatchCouponLog($tGiveCoupon)){
                return false;
            }
        }

        return true;
    }

    /**
     * 拒绝接单
     */
//    public function refuse(){
//        //表单验证
//        $vConf = array(
//            array('id', 'id', 'required|is_natural_no_zero'),
//            array('note', '操作备注', 'required'),
//        );
//        $this->formDataValidation($vConf);
//        $id = (int)post('id');
//        $note = trim(post('note'));
//        $tA = $this->_accept_refuse($id, $note);
//        if ($tA){
//            $this->appReturn(1, '拒绝成功');
//        }
//        $this->appReturn(0, '拒绝失败');
//    }

    /**
     * 取消订单
     */
    public function cancelOrder(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
            array('note', '操作备注', 'required'),
        );
        $this->formDataValidation($vConf);
        $id = (int)post('id');
        // 查看订单是否存在
        $info = $this->mOrder->getInfo($id, 0, 0, true);
        if (empty($info)){
            $this->ajaxReturn(0, '订单不存在');
        }
        if ($info['status'] != 1){
            $this->ajaxReturn(0, '不能取消订单');
        }
        $status = 7;
        $this->db->trans_begin();
        $tA = $this->mOrder->save(array('status' => $status), 0, $id);
        if (!$tA){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }
        //商品增加库存
        $this->loadModel('AdmSettingModel', 'mSet','admin');
        $reduce_stock = $this->mSet->get('reduce_stock');

        if ($reduce_stock == 1){
            //下单时减少
            $result = $this->mOrder->reduceStocks($id, true);
            if($result['status'] == 0){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, $result['message']);
            }
        }
        // 操作记录
        $note = trim(post('note'));
        $rS = $this->mOrder->saveOrderLog($id, '交易关闭', $note,$this->port, $this->userId);
        if (!$rS){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }
        $this->db->trans_commit();
        $backD = array(
            'buttons' => $this->mOrder->status($status, false, true), // 操作按钮
            'status_format_str' => $this->mOrder->STATUS($status, true)
        );
        $this->ajaxReturn(1, '保存成功', $backD);
    }

    /**
     * 删除订单
     */
    public function deleteOrder(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        if (empty($_POST)){
            $this->formDataValidation($vConf, array('id' => get('id')));
            $id = (int)get('id');
            $url = '';
        }else{
            $this->formDataValidation($vConf);
            $id = (int)post('id');
            $url = getUrl('order/home');
        }

        // 查看订单是否存在
        $info = $this->mOrder->getInfo($id, 0, 0, true);
        if (empty($info)){
            $this->ajaxReturn(0, '订单不存在');
        }
        if ($info['status'] != 7){
            $this->ajaxReturn(0, '不能删除订单');
        }
        $this->db->trans_begin();
        $tA = $this->mOrder->deleteOrder($id);
        if (!$tA){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '删除失败');
        }
        $rS = $this->mOrder->deleteOrderLog($id);
        if (!$rS){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '删除失败');
        }
        $this->db->trans_commit();
        $this->ajaxReturn(1, '删除成功', 'order', $url);
    }

    /**
     * 确认收货
     */
    public function confirmReceipt(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
            array('note', '操作备注', 'required'),
        );
        $this->formDataValidation($vConf);
        $id = (int)post('id');

        $info = $this->mOrder->getInfo($id);

        if($info['status'] != 3){
            $this->appReturn(0, '订单不符合送达');
        }
        if ($info['shipping_type'] == 2 && $info['expense_type'] == 1) {
            //查询配送端 订单状态
            $this->loadModel('DlnOrderModel', 'mDlnOrder', 'deliveryman');
            $this->db->select('id,status')
                ->where('order_id', $id);
            $dlnInfo = $this->mDlnOrder->getOne($this->mDlnOrder->tbOrder);
            if ($dlnInfo['status'] == 1) {
                $this->appReturn(0, '该订单未接单，无法确认收货');
            }
        }
        $this->db->trans_begin();
        $result = $this->mOrder->_confirmReceipt($id, trim(post('note')), 0, $this->port, $this->userId);
        if($result['status'] == 0){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, $result['message']);
        }
        $status = 4;
        $backD = array(
            'buttons' => $this->mOrder->status($status, false, true), // 操作按钮
            'status_format_str' => $this->mOrder->STATUS($status, true)
        );
        //减库存
        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
        $reduce_stock = $this->mSetting->get('reduce_stock');

        if($reduce_stock == 2){//发货减库存
            $result = $this->mOrder->reduceStocks($id);

            if($result['status'] == 0){
                $this->db->trans_rollback();
                $this->appReturn(0, $result['message']);
            }
        }
        //增加销量
        $productList = $this->mOrder->getOrderProductList($id);

        $this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');
        foreach ($productList as $v){
            if ($v['variant_id'] > 0){
                $query = $this->mProduct->savePropertyVariant(array('sale_quantity'=>$v['v_sale_quantity'] + $v['quantity']),$v['product_id'],$v['variant_id']);
                if(!$query){
                    $this->db->trans_rollback();
                    $this->appReturn(0,'销量增加失败');
                }
            }
            $qy = $this->mProduct->save(array('sale_quantity'=>$v['sale_quantity']+ $v['quantity']), $v['product_id']);
            if(!$qy){
                $this->db->trans_rollback();
                $this->appReturn(0,'销量增加失败');
            }
        }
        //用户推送消息
        $msgData = array(
            'title' => '订单已送达',
            'content' => '订单已送达',
            'addtime' => time(),
        );
        $this->loadModel('ConsumerMessageModel', 'mMessage', 'consumer');
        if(!($this->mMessage->save($msgData, 0, $id))){
            $this->db->trans_rollback();
            $this->appReturn(0, '消息保存失败');
        }
        //获取消息id
        $msgInfo = $this->mMessage->getInfo(0, 0, 0, $id);
        if (!empty($msgInfo)) {
            //删除消息查看记录
            $this->mMessage->deleteView($info['consumer_id'], $msgInfo['id']);
        }
        jpush($msgData['title'], $msgData['content'], 1, array($info['jpush_code']), 3, $id, $info['expense_type']);

        //商家推送消息
        $this->loadModel('merchantMessageModel', 'mMerMsg', 'merchant');
        if(!($this->mMerMsg->save($msgData, 0, $id))){
            $this->db->trans_rollback();
            $this->appReturn(0, '消息保存失败');
        }
        //获取消息id
        $msgIn = $this->mMerMsg->getInfo(0, 0, $id);
        if (!empty($msgIn)) {
            //删除消息查看记录
            $this->mMerMsg->deleteView($info['merchant_id'], $msgIn['id']);
        }
        MerchantJpush($msgData['title'], $msgData['content'], 1, array($info['merchant_jpush_code']), 3, $id);
        $this->db->trans_commit();
        $this->ajaxReturn(1, '保存成功', $backD);
    }

    /**
     * 申请售后
     */
    public function customerService(){
        //表单验证
        $vConf = array(
            array('order_id', 'id', 'required|is_natural_no_zero'),
//            array('id', 'id', 'required|is_natural_no_zero'),
            array('refund_amount', '退款金额', 'required|is_numeric'),
            array('reason', '售后原因', 'required'),
            array('remark', '原因描述', 'required'),
            array('note', '操作备注', 'required'),
        );
        $this->formDataValidation($vConf);
        $orderId = (int)post('order_id');
//        $id = (int)post('id');
        $refundAmount = post('refund_amount');
        $images 		= post('img');
        // 查看订单是否存在
        $info = $this->mOrder->getInfo($orderId);
        if (empty($info)){
            $this->ajaxReturn(0, '订单不存在');
        }
        if ($info['status'] != 2 && $info['status'] != 3 && $info['status'] != 4){
            $this->ajaxReturn(0, '不能申请售后');
        }
        //限制售后次数
        $serviceCount = $this->mOrder->hasOrderServiceCount($orderId, $this->userId);
        if($serviceCount >= 2){
            $this->ajaxReturn(0, '已达申请售后次数上限，请联系平台');
        }
        if ($info['after_sale'] == 2){
            $this->ajaxReturn(0, '已经申请售后，请勿重复申请');
        }
        if ($refundAmount > $info['reality_amount']){
            $this->ajaxReturn(0, '退款金额不能大于'.$info['reality_amount'].'元');
        }

        // 修改商品售后状态
        $this->db->trans_begin();
        $op = $this->mOrder->save(array('after_sale' => 2), 0, $orderId);
        if (!$op){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }
        // 添加售后订单
        $data = array(
            'merchant_id' => $info['merchant_id'],
            'consumer_id' => $info['consumer_id'],
            'code' => getOrderCode(),
            'refund_amount' => $refundAmount,
            'order_id' => $orderId,
            'order_status' => $info['status'],
//            'order_product_id' => $id,
//            'variant_id' => $opInfo['variant_id'],
            'reason' => trim(post('reason')),
            'remark' => trim(post('remark')),
            'status' => 3,
            'addtime' => time()
        );
        $tA = $this->mOrder->saveService($data);
        if (!$tA){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }
        if ($images){
            $imgPath = array();
            $path = 'uploads/product/service/'.$tA.'/';
            foreach ($images as $k=>$v){
                if (stripos($v,'temp') !== FALSE){
                    $size = getimagesize($v);
                    $imgPath[] = saveTempImg($v,$path,true, $size[0], $size[1]);
                }else {
                    $imgPath[] = str_replace(base_url(), '', $v);
                }
            }

            $imgPath = array_slice($imgPath, 0, 3);
            //保存
            $query = $this->mOrder->saveService(array('pic'=>json_encode($imgPath)), 0, $tA);
            if( ! $query){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '保存失败');
            }
        }
        // 添加操作记录
        $note = trim(post('note'));
        $rS = $this->mOrder->saveOrderLog($orderId, '售后中', $note,$this->port, $this->userId);
        if (!$rS){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }
        $tMerchant = $this->mMerchant->getMiniInfo($info['merchant_id']);
        //给商家的推送消息
        $title = '您有一条售后订单';//商家消息标题
        $merMsg = array(
            'merchant_id'=>$info['merchant_id'],
            'type'=>4,
            'order_id'=>$tA,
            'title'=>$title,
            'content'=>'消费者于'.date('Y/m/d H:i:s').'对订单商品申请售后服务！请及时前往处理',
            'addtime'=>time(),
        );

        //保存商家消息
        $this->loadModel('MerchantMessageModel', 'mMMessage', 'merchant');
        if ( ! $msgId = $this->mMMessage->save($merMsg)){
            $this->db->trans_rollback();
            $this->appReturn(0,'保存失败');
        }
        $this->db->trans_commit();
        //通知商家
        MerchantJpush($title,$title,1,$tMerchant['jpush_code'],4, $orderId);
        $this->ajaxReturn(1, '保存成功');
    }

    /**
     * 修改收货信息
     */
    public function addressEdit(){
        //表单验证
        $vConf = array(
            array('order_id', 'order_id', 'required|is_natural_no_zero'),
            array('contacts', '联系人', 'required'),
            array('mobile', '联系方式', 'required|valid_mobile'),
            array('address', '地址详情', 'required'),
            array('province_id', '省份', 'required|is_natural_no_zero'),
            array('city_id', '城市', 'required|is_natural_no_zero'),
            array('county_id', '区县', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf);
        $id = (int)post('order_id');
        $provinceId = (int)post('province_id');
        $cityId = (int)post('city_id');
        $countyId = (int)post('county_id');
        // 查看订单是否存在
        $info = $this->mOrder->getInfo($id);
        if (empty($info)){
            $this->ajaxReturn(0, '订单不存在');
        }
        $this->loadModel('AdmSettingModel', 'mAdm', 'admin');
        $loc = $this->mAdm->getLocationNameByIds(array($provinceId, $cityId, $countyId));
        if (count($loc) != 3){
            $this->ajaxReturn(0, '区域数据错误');
        }
        $data = array(
            'contacts' => trim(post('contacts')),
            'mobile' => trim(post('mobile')),
            'address' => trim(post('address')),
            'province_id' => $provinceId,
            'city_id' => $cityId,
            'county_id' => $countyId,
        );

        $tA = $this->mOrder->save($data, 0, $id);
        if (!$tA){
            $this->ajaxReturn(0, '保存失败');
        }
        $backD = array(
            'contacts' => $data['contacts'],
            'mobile' => $data['mobile'],
            'region' => $loc[$provinceId]['name'].' - '.$loc[$cityId]['name'].' - '.$loc[$countyId]['name'],
            'address' => $data['address'],
            'expense_type_str' => $info['expense_type_str']
        );
        $this->ajaxReturn(1, '保存成功', $backD);
    }

    /**
     * 导出
     */
    public function export(){
        $filename = '订单管理'.date('Y-m-d',time()).'.csv';
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo mb_convert_encoding('订单号,编号,商家名称,会员名称,消费模式,支付方式,订单金额,实付金额,下单时间,支付时间,状态','gb2312','utf-8')."\n";
        $pageNumber = 500;
        $page = 1;
        while(true){
            $data = $this->mOrder->adminPcGetOrderList(0, 0, array(), array('page' => $page, 'pageNumber' => $pageNumber));
            if(empty($data)){
                break;
            }
            $page ++;
            foreach($data as $v){
                $expenseType = $this->mOrder->expenseType($v['expense_type']);
                $payType = $this->mOrder->payType($v['pay_type']);
                $addtime = dateFormat($v['addtime']);
                $paytime = $v['pay_time']?date('Y-m-d H:i', $v['pay_time']):'';
                $merchant_day_index = $v['merchant_day_index']?'#'.$v['merchant_day_index']:'';
                if ($v['expense_type'] == 2){
                    $status = $this->mOrder->storeStatus($v['status']);
                }else{
                    $status = $this->mOrder->status($v['status']);
                }
                echo mb_convert_encoding($v['code']."\t".','.$merchant_day_index.','.$v['merchant'].','.$v['consumer']."\t".','.$expenseType.','.$payType.','.$v['total_amount'].','.$v['reality_amount'].','.$addtime.','.$paytime.','.$status, 'gb2312','utf-8')."\n";
            }
        }
    }
}
